<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <!-- 主表单区域 -->
      <a-form :form="form">
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-item label="商品id" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-popup
                v-decorator="['goodsName']"
                :trigger-change="true"
                org-fields="id,name"
                dest-fields="goodsId,goodsName"
                code="goods_select"
                :multi="false"
                @callback="popupCallback"/>

            </a-form-item>
            <a-form-item label="goodsId"  style="height: 0px;overflow: hidden;margin-bottom: 0">
              <a-input v-decorator="['goodsId']" ></a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['title', validatorRules.title]" placeholder="请输入标题"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择开始时间"  v-decorator="['startTime', validatorRules.startTime]" :trigger-change="true" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
              <!--<a-date-picker
                format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="disabledDate"
                showTime
                v-decorator="['startTime', validatorRules.startTime]"
                style="width: 100%"
                :trigger-change="true"
              />-->
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择结束时间" v-decorator="['endTime', validatorRules.endTime]" :trigger-change="true" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"/>
              <!--<a-date-picker
                format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="disabledDate"
                showTime
                v-decorator="['endTime', validatorRules.endTime]"
                style="width: 100%"
                :trigger-change="true"
              />-->
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="商品状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="radioButton" disabled v-decorator="['status', validatorRules.status]" :trigger-change="true" dictCode="goods_status" placeholder="请选择商品状态"/>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="新品状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="radioButton" :trigger-change="true"  v-decorator="['newStatus', validatorRules.newStatus]"  dictCode="new_status" placeholder="请选择新品状态"/>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="推荐状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="radioButton" v-decorator="['recommandStatus', validatorRules.recommandStatus]" :trigger-change="true" dictCode="recommand_status" placeholder="请选择推荐状态"/>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="售卖类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="radioButton" v-decorator="['sale_type', validatorRules.sale_type]" :trigger-change="true" dictCode="sale_type" placeholder="请选择售卖类型"/>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="初始售卖" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['initSale', validatorRules.initSale]" placeholder="请输入初始售卖" :min="0" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="限购数量" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['limitSale', validatorRules.limitSale]" placeholder="请输入限购数量" :min="0" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="排序" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['sort', validatorRules.sort]" placeholder="请输入排序" :min="1" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="佣金" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['commission', validatorRules.commission]" :min="1" placeholder="请输入佣金" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="积分" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['integral', validatorRules.integral]" :min="0" placeholder="请输入积分" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-item label="关键字" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['keywords', validatorRules.keywords]" placeholder="请输入关键字" style="width: 100%"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>

      <!-- 子表单区域 -->
      <a-tabs v-model="activeKey" @change="handleChangeTabs" >
        <a-tab-pane tab="上架商品明细" :key="refKeys[0]" :forceRender="true">
          <j-editable-table
            :ref="refKeys[0]"
            :loading="goodsShelfDetailTable.loading"
            :columns="goodsShelfDetailTable.columns"
            :dataSource="goodsShelfDetailTable.dataSource"
            :maxHeight="300"
            :goodsIds="goodsIds"
            :rowNumber="true"
            :rowSelection="true"
            :actionButton="true"/>
        </a-tab-pane>

      </a-tabs>

    </a-spin>
  </j-modal>
</template>

<script>

  import pick from 'lodash.pick'
  import moment from 'moment';
  import { FormTypes,getRefPromise } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { validateDuplicateValue } from '@/utils/util'
  import JDate from '@/components/jeecg/JDate'
  import JDictSelectTag from "@/components/dict/JDictSelectTag"
  import { getAction } from '@api/manage'

  export default {
    name: 'GoodsShelfModal',
    mixins: [JEditableTableMixin],
    components: {
      JDate,
      JDictSelectTag,
    },
    watch:{
      goodsShelfDetailTable:{
        handler(newVal) {
          console.log(newVal)

        },
        deep: true,
        immediate: false,
      },
      optionsArray:{
        handler(newVal) {
          console.log(newVal)
          this.goodsShelfDetailTable.columns[0].options = newVal
        },
        deep: true,
        immediate: false,
      }
    },
    created() {
      // this.goodsShelfDetailTable.columns[0].options = this.optionsArray
    },
    data() {
      return {
        tableShow:false,
        optionsArray:[
          {
            text:'1111',
            value:1111
          },
          {
            text:'2222',
            value:2222
          }
        ],
        goodsIds:[],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          sale_type:{
            initialValue:'0',
            rules: [
              { required: true, message: '请输入商品id!'},
            ]
          },
          goodsId: {
            rules: [
              { required: true, message: '请输入商品id!'},
            ]
          },
          title: {
            rules: [
              { required: true, message: '请输入标题!'},
            ]
          },
          startTime: {
            rules: [
              { required: true, message: '请输入开始时间!'},
            ]
          },
          endTime: {
            rules: [
              { required: true, message: '请输入结束时间!'},
            ]
          },
          status: {
            initialValue:'0',
            rules: [
              { required: true, message: '请输入商品状态[-1：已删除0:已下架,1:已上架]!'},
              { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},
            ]
          },
          newStatus: {
            initialValue:'0',
            rules: [
              { required: true, message: '请输入新品状态[0:非新品,1:新品]!'},
              { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},
            ]
          },
          recommandStatus: {
            initialValue:'0',
            rules: [
              { required: true, message: '请输入推荐状态[0:不推荐,1:推荐]!'},
              { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},
            ]
          },
          sort: {
            rules: [
              { required: true, message: '请输入排序!'},
              { pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},
            ]
          },
          commission: {
            rules: [
              { required: true, message: '请输入佣金!'},
              { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!'},
            ]
          },
          integral: {
            rules: [
              { required: false},
              { pattern: /^-?\d+$/, message: '请输入整数!'},
            ]
          },
        },
        refKeys: ['goodsShelfDetail', ],
        tableKeys:['goodsShelfDetail', ],
        activeKey: 'goodsShelfDetail',
        // 上架商品明细
        goodsShelfDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '商品规格id',
              key: 'goodsSpecsId',
              type: FormTypes.select,
              options:[],
              width:"200px",
              placeholder: '请选择${title}',
              defaultValue: '',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '上架数量',
              key: 'quantity',
              type: FormTypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '单位',
              key: 'unit',
              type: FormTypes.select,
              dictCode:"unit",
              width:"200px",
              placeholder: '请选择${title}',
              defaultValue: '',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '商品重量',
              key: 'weight',
              type: FormTypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '售价',
              key: 'suggestedPrice',
              type: FormTypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '团购价格',
              key: 'groupPurchasePrice',
              type: FormTypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
          ]
        },
        url: {
          add: "/goods/goodsShelf/add",
          edit: "/goods/goodsShelf/edit",
          goodsShelfDetail: {
            list: '/goods/goodsShelf/queryGoodsShelfDetailByMainId'
          },
          queryByGoodsId:"goodsspecs/bizGoodsSpecs/queryByGoodsId/"
        }
      }
    },
    methods: {
      moment,
      handleChangeTab(key) {
        this.$refs[`editableTable${key}`].resetScrollTop()
      },
      disabledDate(current) {
        // Can not select days before today and today
        return current && current < moment().endOf('time');
      },
      disabledDateTime() {
        return {
          disabledHours: () => this.range(0, 24).splice(4, 20),
          disabledMinutes: () => this.range(30, 60),
          disabledSeconds: () => [55, 56],
        };
      },

      getFormFieldValue(field){
        return this.form.getFieldValue(field)
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        let fieldval = pick(this.model,'goodsId','sale_type','goodsName','keywords','limitSale','initSale','title','startTime','endTime','status','newStatus','recommandStatus','sort','commission','integral')
        this.$nextTick(() => {
          this.form.setFieldsValue(fieldval)
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.goodsShelfDetail.list, params, this.goodsShelfDetailTable)
        }
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)

        return {
          ...main, // 展开
          goodsShelfDetailList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
     popupCallback(row){
       this.form.setFieldsValue(pick(row,'goodsId','goodsName','title','startTime','endTime','status','newStatus','recommandStatus','sort','commission','integral'))
       this.optionsArray= []
       let ccc = this.form.getFieldValue('goodsId')
       getAction(this.url.queryByGoodsId+ccc).then((res)=>{
         console.log(res)
         if (res.success){
            if (res.result){
              for (let res of res.result) {
                let obj = {}
                let obj1 = {}
                obj.id = res.id
                obj.stock = res.stock
                obj1.text = res.stock
                obj1.value = res.id
                for (let argument of res.specsValues) {
                  if (argument.attributeName !== 'sortNum' && argument.attributeName !== 'image'){
                    obj.specsValues = argument
                  }
                }
                this.goodsIds.push(obj)
                this.optionsArray.push(obj1)
              }

              this.goodsShelfDetailTable.columns[0].options = this.optionsArray
              // console.log('this.optionsArray',this.optionsArray)
              // this.tableShow = true
              this.$refs.goodsShelfDetail.initialize()
            }else {
              this.$message.error('该商品没有规格！')
            }
         }else {
            this.$message.error(res.message)
         }



       })
     },

    }
  }
</script>

<style scoped>
</style>